#include <iostream>
#include <string>
#include <ctime>
#include <cassert>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"

int main(int argc, char *argv[]) 
{
    if(argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " <host> <port>" << std::endl;
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    Sock sockfd;
    sockfd.Socket();
    bool ret = sockfd.Connect(serverip, serverport);
    if(!ret) return 1;

    srand(time(nullptr) ^ getpid());
    int cnt = 1;
    const std::string opers = "+-*/%&|^=";

    std::string inbuffer_stream;
    while (cnt <= 5)
    {
        std::cout << "================ 第" << cnt++ << "次测试 ====================\n";
        int x = rand() % 100 + 1;
        usleep(1234);
        int y = rand() % 100;
        usleep(4321);
        char op = opers[rand() % opers.size()];

        Request req(x, y, op);
        req.DebugPrint();

        std::string package;
        req.Serialization(&package);
        package = Encode(package);

        std::cout << "这是最新的请求：\n" << package;
        write(sockfd.Fd(), package.c_str(), package.size());    // 模拟发送多次请求
        // write(sockfd.Fd(), package.c_str(), package.size());    
        // write(sockfd.Fd(), package.c_str(), package.size());    
        // write(sockfd.Fd(), package.c_str(), package.size());    


        char buffer[128];
        ssize_t n = read(sockfd.Fd(), buffer, sizeof(buffer));   // 读取响应（计算结果）
        if(n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer;
            do
            {
                std::string content;
                bool ret = Decode(inbuffer_stream, &content);
                assert(ret);

                Response resp;
                ret = resp.Deserialization(content);        
                assert(ret);

                resp.DebugPrint();
                // std::cout << "\n";
            } while (ret && !inbuffer_stream.empty());                    
        }
        std::cout << "=================================================\n\n"; 
        sleep(1);
    }
    sockfd.Close();
    return 0;
}